window.addEventListener('load', function () {
  // 初始化
  iniData('山东省', '济南市', '历下区')
  function iniData(province, city, county) {
    // 获取元素
    let provinceDOM = document.querySelector('#province')
    let cityDOM = document.querySelector('#city')
    let countyDOM = document.querySelector('#county')
    // 准备一个空数组放省下面的市
    let selectShi = []

    // 准备一个空数组放市下面的区
    let selectQu = []

    let srtHtml = '<option value="">请选择省份</option>'

    // 循环遍历
    for (let i = 0; i < DataList.length; i++) {
      // 每一项
      const element = DataList[i];
      srtHtml += `<option value="${element.value}">${element.value}</option>`

    }
    provinceDOM.innerHTML = srtHtml
    // 省份的默认值
    provinceDOM.value = province
    //  渲染市
    renderShi(province)

    cityDOM.value = city

    // 渲染区
    renderQu(city)
    countyDOM.value = county




    // 监听省是否切换了 用change事件
    provinceDOM.addEventListener('change',function() {
      renderShi(this.value)
    })
      
    cityDOM.addEventListener('change',function() {
      renderQu(this.value)
    })

    function renderQu(city) {
      // 遍历
      for (let i = 0; i < selectShi.length; i++) {
        const element = selectShi[i];
        // 判断
        if (city === element.value) selectQu = element.children
      }

      // 判断 显示与隐藏
       if(!selectQu) {
        countyDOM.parentNode.style.display = 'none'
        return
       }else {
        countyDOM.parentNode.style.display = 'block'
       }
      // 生成区的html
      let srtQuHtml = `<option value="">请选择区县</option>`
      // 遍历
      for (let i = 0; i < selectQu.length; i++) {
        const element = selectQu[i];
        srtQuHtml += `<option value="${element.value}">${element.value}</option>`
      }
      // 将生成的html赋值给dom对象
      countyDOM.innerHTML = srtQuHtml
    }


    function renderShi(sheng) {
      // 根据省找到市
      // 遍历
      for (let i = 0; i < DataList.length; i++) {

        if (sheng === DataList[i].value) selectShi = DataList[i].children
      }


      let srtShiHtml = '<option value="">请选择城市</option>'
      // 循环遍历
      for (let i = 0; i < selectShi.length; i++) {
        // 每一项
        const element = selectShi[i];
        srtShiHtml += `<option value="${element.value}">${element.value}</option>`

      }
      console.log(srtShiHtml)

      cityDOM.innerHTML = srtShiHtml
    }
  }
})